package com.useeinfo.oa.open.admin;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.useeinfo.framework.sugar.data.QueryParam;
import com.useeinfo.framework.sugar.data.SelectVO;
import com.useeinfo.framework.sugar.tools.DateTimeUtils;
import com.useeinfo.framework.sugar.tools.StringConverters;
import com.useeinfo.oa.common.utils.ResultUtil.ResultDto;
import com.useeinfo.oa.common.utils.ResultUtil.ResultUtil;
import com.useeinfo.oa.modules.base.biz.*;
import com.useeinfo.oa.modules.base.entity.*;
import com.useeinfo.oa.modules.base.enums.AuditTypeEnum;
import com.useeinfo.oa.modules.base.enums.NodeTypeEnum;
import com.useeinfo.oa.modules.security.biz.OrganizationBiz;
import com.useeinfo.oa.modules.security.biz.SystemUserBiz;
import com.useeinfo.oa.modules.security.entity.SystemUser;
import com.useeinfo.oa.modules.security.util.SessionKeyUtils;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.List;

@Controller
@RequestMapping("/web/admin/auditFlow")
public class AuditFlowManageAction {
    @Autowired
    private AuditFlowBiz auditFlowBiz;
    @Autowired
    private EnterpriseBiz enterpriseBiz;
    @Autowired
    private AuditNodeBiz auditNodeBiz;
    @Autowired
    private ApplicationModuleBiz applicationModuleBiz;
    @Autowired
    private OrganizationBiz organizationBiz;
    @Autowired
    private PositionBiz positionBiz;
    @Autowired
    private SystemUserBiz systemUserBiz;

    @RequestMapping("/list")
    public ModelAndView list() {

        ModelAndView modelAndView = new ModelAndView();
        modelAndView.setViewName("pages/admin/auditFlow/auditFlowList");
        //查询审批流类型枚举类
        JSONArray auditTypeArray = new JSONArray();
        for(AuditTypeEnum auditTypeEnum : AuditTypeEnum.values()){
            JSONObject json = new JSONObject();
            json.put("name",auditTypeEnum.getName());
            json.put("code",auditTypeEnum.getCode());
            auditTypeArray.add(json);
        }
        modelAndView.addObject("auditTypeArray", auditTypeArray);
        return modelAndView;
    }

    @RequestMapping("/listJson")
    @ResponseBody
    public JSONObject listJson(@RequestParam(value = "pageNo", required = false) String pageNowParam,
                               @RequestParam(value = "pageSize", required = false) String pageSizeParam,
                               @RequestParam(value = "searchCode", required = false) String searchCode,
                               @RequestParam(value = "applicationName", required = false) String applicationName,
                               @RequestParam(value = "auditType", required = false) String auditType,
                               @RequestParam(value = "orderBy", required = false) String orderBy,HttpServletRequest request) {
        QueryParam queryParam = new QueryParam(pageNowParam, pageSizeParam);
        queryParam.getSqlMap().put("searchCode", searchCode);
        queryParam.getSqlMap().put("applicationName", applicationName);
        queryParam.getSqlMap().put("auditType", auditType);
        if (StringUtils.isNotBlank(orderBy)) {
            if (orderBy.equals("applicationName asc")) {
                queryParam.setSqlOrder("order by " + "s.applicationModule.applicationName asc");
            } else if (orderBy.equals("applicationName desc")) {
                queryParam.setSqlOrder("order by " + "s.applicationModule.applicationName desc");
            } else  if (orderBy.equals("enterpriseName asc")) {
                queryParam.setSqlOrder("order by " + "s.enterprise.enterpriseName asc");
            } else if (orderBy.equals("enterpriseName desc")) {
                queryParam.setSqlOrder("order by " + "s.enterprise.enterpriseName desc");
            } else {
                queryParam.setSqlOrder("order by " + orderBy);
            }

//
        }
        Enterprise enterprise = SessionKeyUtils.getSessionEnterprise(request);
        if(enterprise!=null){
            queryParam.getSqlMap().put("enterpriseId", enterprise.getId()+"");
        }
        return auditFlowBiz.findJSONList(queryParam);
    }

    //编辑审批流
    @RequestMapping("/editPage")
    public ModelAndView editPage(String id) {

        ModelAndView modelAndView = new ModelAndView();
        AuditFlow auditFlow = auditFlowBiz.findModel(StringConverters.null2Long(id));
        modelAndView.addObject("auditFlow", auditFlow);
        modelAndView.addObject("type", auditFlow!=null?auditFlow.getAuditTypeEnum().getCode():"COMPLETE");
        modelAndView.setViewName("pages/admin/auditFlow/auditFlowEditPart");

        return modelAndView;
    }

    @RequestMapping("/nodeJson")
    @ResponseBody
    public JSONObject nodeJson(String nodeId,String flowId) {
            QueryParam queryParam = new QueryParam("-1","-1");
            queryParam.getSqlMap().put("flowId", flowId);
            if(StringUtils.isNotBlank(nodeId)){
                queryParam.getSqlMap().put("id", nodeId);
            }
             List<AuditNode> auditNodeList=auditNodeBiz.findList(queryParam);
             JSONObject rows=new JSONObject();
            JSONArray jsonArray=new JSONArray();
            auditNodeList.forEach(auditNode ->{
                JSONObject jsonObject=auditNodeBiz.getNodeJson(auditNode);
                jsonArray.add(jsonObject);
            });
            rows.put("list",jsonArray);
            rows.put("count",auditNodeList.size());
            return rows;

    }

    //编辑审批流的节点
    @RequestMapping("/editNodePage")
    public ModelAndView editNodePage(String id) {

        ModelAndView modelAndView = new ModelAndView();
        AuditFlow auditFlow = auditFlowBiz.findModel(StringConverters.null2Long(id));
        modelAndView.addObject("auditFlow", auditFlow);
        modelAndView.addObject("auditNodeList", auditNodeBiz.orderByList(id));
        modelAndView.setViewName("pages/admin/auditFlow/auditNode");
        return modelAndView;
    }

    //新增节点
    @RequestMapping("/addNodeDetail")
    public ModelAndView addNodeDetail(String id, String nodeId,String parentId) {

        ModelAndView modelAndView = new ModelAndView();

        AuditNode auditNode = auditNodeBiz.findModel(StringConverters.null2Long(nodeId));
        modelAndView.addObject("auditNode", auditNode);
        modelAndView.addObject("flowId", id);
        modelAndView.addObject("parentId", parentId);
        List<String> nodeType=new ArrayList<>();
        nodeType.add(NodeTypeEnum.USER.getCode());
        nodeType.add(NodeTypeEnum.POSITION.getCode());
        AuditFlow auditFlow=auditFlowBiz.findModel(StringConverters.null2Long(id));
        if(auditFlow.getApplicationModule().getRemark().equals("REPAIR")){
            //只有维修模块和自动报修才有指定本人
            nodeType.add(NodeTypeEnum.SELF.getCode());
        }
        modelAndView.addObject("nodeType",nodeType);
        modelAndView.setViewName("pages/admin/auditFlow/editNode");

        return modelAndView;
    }

    //保存节点
    @RequestMapping("/saveNode")
    @ResponseBody
    public ResultDto saveNode(AuditNode auditNode, HttpServletRequest request, String flowId, String parent,
                              @RequestParam(value = "select_position[]", required = false) List<String> select_position,
                              @RequestParam(value = "select_organization[]", required = false) List<String> select_organization,
                              @RequestParam(value = "select_user[]", required = false) List<String> select_user,
                              @RequestParam(value = "name", required = false) String name,
                              @RequestParam(value = "type", required = false) String nodeType) {
        Enterprise enterprise= SessionKeyUtils.getSessionEnterprise(request);
        if(enterprise==null){
            return ResultUtil.error("登陆过期，请重新登录");
        }
        SystemUser systemUser = SessionKeyUtils.getSessionUser(request);
        if (systemUser == null) {
            return ResultUtil.error("登陆过期，请重新登录");
        }
        if(StringUtils.isBlank(parent)&&auditNode.getId()==null){
            parent="-1";
        }
        if (StringUtils.isNotBlank(parent)) {//parentId
            auditNode.setParentId(StringConverters.null2Long(parent));
        }
        if(StringUtils.isNotBlank(name)){
            auditNode.setNodeName(name);
        }
        if ("POSITION".equals(nodeType)) {
            auditNode.setOrganizationId(select_organization.get(0));
            auditNode.setRelationId(select_position.get(0));
            auditNode.setNodeTypeEnum(NodeTypeEnum.POSITION);
        }
        else if ("USER".equals(nodeType)) {
            auditNode.setOrganizationId(select_organization.get(0));
            auditNode.setRelationId(select_user.get(0));
            auditNode.setNodeTypeEnum(NodeTypeEnum.USER);
        }else{
            auditNode.setNodeTypeEnum(NodeTypeEnum.SELF);
        }

       return auditNodeBiz.saveNode(auditNode,parent,flowId);

    }

    //删除节点
    @RequestMapping("/deleteNode")
    @ResponseBody
    public ResultDto deleteNode(String id,String flowId) {
        AuditNode auditNode=auditNodeBiz.findModel(StringConverters.null2Long(id));
        auditNodeBiz.pushAfterNode(auditNode);
        auditNodeBiz.deleteLogic(auditNode);
        //保存完整审批节点
        auditFlowBiz.saveAllTree(flowId);
        return ResultUtil.success();
    }



    /**
     * 新增审批流
     * @param auditFlow 审批流
     * @param request
     * @param select_application 应用企业的ids   （目前只是单选，下面的逻辑也没有做多企业应用插入）
     * @param auditType 审批的类型
     * @return ResultDto
     */
    @RequestMapping("/addOrUpdate")
    @ResponseBody
    public ResultDto addOrUpdate(AuditFlow auditFlow, HttpServletRequest request,
                                 @RequestParam(value = "select_application[]", required = false) List<String> select_application,
                                 @RequestParam(value = "auditType", required = false) String auditType) {
        Enterprise enterprise= SessionKeyUtils.getSessionEnterprise(request);
        if(enterprise==null){
            return ResultUtil.error("登陆过期，请重新登录");
        }
        auditFlow.setEnterprise(enterprise);
        SystemUser systemUser = SessionKeyUtils.getSessionUser(request);
        if (systemUser == null) {
            return ResultUtil.error("登陆过期，请重新登录");
        }
        //保存审批类型
        if ("delay".equals(auditType)) {
            auditFlow.setAuditTypeEnum(AuditTypeEnum.DELAY);
        } else if ("complete".equals(auditType))  {
            auditFlow.setAuditTypeEnum(AuditTypeEnum.COMPLETE);
        }else{
            auditFlow.setAuditTypeEnum(AuditTypeEnum.CANCEL);
        }
        auditFlow.setCreateUser(systemUser);
        if (CollectionUtils.isNotEmpty(select_application)) {
            ApplicationModule applicationModule = applicationModuleBiz.findModel(StringConverters.null2Long(select_application.get(0)));
            auditFlow.setApplicationModule(applicationModule);
        }
        //更改默认审批流
        if(auditFlow.getDefaultV()){
            auditFlowBiz.updateDefault(auditFlow.getApplicationModule().getId()+"",auditFlow.getAuditTypeEnum().getCode()+"");
        }

        auditFlowBiz.addOrUpdate(auditFlow);
        return ResultUtil.success();
    }

    //删除审批流
    @RequestMapping("/delete")
    @ResponseBody
    public ResultDto delete(String id) {
        auditFlowBiz.deleteLogic(auditFlowBiz.findModel(StringConverters.null2Long(id)));

        return ResultUtil.success();
    }

    /**
     * 获取审批流选择数据
     *
     * @param q
     * @return
     */
    @RequestMapping("/getAuditFlowSelect")
    @ResponseBody
    public List<SelectVO> getAuditFlowSelect(@RequestParam(value = "q", required = false) String q,
                                             @RequestParam(value = "id", required = false) String id,HttpServletRequest request, String type,int flag) {
        //下面保证默认选择项加载正常
        String index = "";
        boolean status = false;//表示默认list中无此id的数据
        List<SelectVO> selectVOS = new ArrayList<>();
        QueryParam queryParam = new QueryParam(1, 20);
        AuditFlow auditFlow = auditFlowBiz.findModel(StringConverters.ToLong(id));
        if(StringUtils.isBlank(q)&&auditFlow!=null){
            index = id;
        }

        queryParam.getSqlMap().put("searchCode", q);
        Enterprise enterprise = SessionKeyUtils.getSessionEnterprise(request);
        if (enterprise != null) {
            queryParam.getSqlMap().put("enterpriseId", enterprise.getId() + "");
        }

        if ("complete".equals(type)) {
            queryParam.getSqlMap().put("complete", "complete");
        } else if ("delay".equals(type)) {
            queryParam.getSqlMap().put("delay", "delay");
        }else if ("cancel".equals(type)) {
            queryParam.getSqlMap().put("cancel", "cancel");
        }
        String moduleType; //1,维修管理，2维护保养，3巡检，0任务工单
        if (flag == 0) {
            moduleType = "TASK";
        } else if (flag == 1) {
            moduleType = "REPAIR";
        } else {
            moduleType = flag == 2 ? "MAINTAIN" : "INSPECTION";
        }
        queryParam.getSqlMap().put("remark",moduleType);
        List<AuditFlow> auditFlows = auditFlowBiz.findList(queryParam);
        if(CollectionUtils.isNotEmpty(auditFlows)){
            for(AuditFlow auditFlow1 : auditFlows){
                if(StringUtils.isNotBlank(index)&&index.equals(auditFlow1.getId()+"")){
                    status = true;
                }
                selectVOS.add(new SelectVO(auditFlow1.getFlowName(), auditFlow1.getId() + ""));
            }
        }
        if(!status&&auditFlow!=null){
            selectVOS.add(new SelectVO(auditFlow.getFlowName(), auditFlow.getId() + ""));
        }
        return selectVOS;
    }


}
